import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        String blogId = req.getParameter("blogId");
        BlogDao blogDao = new BlogDao();
        if (blogId == null){
            List<Blog> blogs = null;
            try {
                blogs = blogDao.selectAll();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            resp.getWriter().write(objectMapper.writeValueAsString(blogs));
        }else{
            try {
                Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
                resp.getWriter().write(objectMapper.writeValueAsString(blog));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 发布博客
        // 1.检查用户的登陆状态
        HttpSession session = req.getSession(false);

        if (session == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(403);
            resp.getWriter().write("当前用户未登录,不能发布博客!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            resp.setContentType("text/html; charset=utf8");
            resp.setStatus(403);
            resp.getWriter().write("当前用户未登录,不能发布博客!");
            return;
        }

        // 2.获取请求中的参数
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");

        // 3.构造blog对象
        Blog blog = new Blog();
        // blogId是自增主键,postTime用now获取过了
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());

        // 4.将博客保存到数据库中
        BlogDao blogDao = new BlogDao();
        try {
            blogDao.insert(blog);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        resp.sendRedirect("blogList.html");
    }
}
